package com.scuec.groupfive.controller;

import com.scuec.groupfive.mapper.WrongQuestionMapper;
import com.scuec.groupfive.service.WrongQuestionService;
import com.scuec.groupfive.service.Favorite_zService;
import com.scuec.groupfive.service.impl.WrongQuestionServiceImpl;
import com.scuec.groupfive.vo.WrongQuestionVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class WrongQuestionController {
    @Resource
    private WrongQuestionService wrongQuestionService;
    
    @Resource
    private WrongQuestionMapper wrongQuestionMapper;
    
    @Resource
    private Favorite_zService favoriteZService;

    public WrongQuestionController(WrongQuestionService wrongQuestionService) {
        this.wrongQuestionService = wrongQuestionService;
    }

    // 1. 按错题次数降序
    @GetMapping("/wrong-questions/by-count/{userId}")
    public ResponseEntity<?> getByWrongCountDesc(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String subjectCode,
            @RequestParam(required = false) String examType) {
        try {
            return ResponseEntity.ok(wrongQuestionService.getByWrongCountDesc(userId, page, size, subjectCode, examType));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取错题列表失败: " + e.getMessage());
        }
    }

    // 2. 按科目和章节分类
    @GetMapping("/wrong-questions/by-subject-chapter/{userId}")
    public ResponseEntity<?> getBySubjectChapter(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String subjectCode,
            @RequestParam(required = false) String examType) {
        try {
            return ResponseEntity.ok(wrongQuestionService.getBySubjectChapter(userId, page, size, subjectCode, examType));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取错题列表失败: " + e.getMessage());
        }
    }

    // 3. 按时间排序
    @GetMapping("/wrong-questions/by-time/{userId}")
    public ResponseEntity<?> getByTimeOrder(
            @PathVariable Long userId,
            @RequestParam(required = false, defaultValue = "false") boolean asc,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String subjectCode,
            @RequestParam(required = false) String examType) {
        try {
            return ResponseEntity.ok(wrongQuestionService.getByTimeOrder(userId, asc, page, size, subjectCode, examType));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取错题列表失败: " + e.getMessage());
        }
    }

    // 4. 更新错题次数
    @PostMapping("/wrong-questions/update-count")
    public String updateWrongCount(
            @RequestParam Long id,
            @RequestParam int newCount) {
        int rows = wrongQuestionService.updateWrongCount(id, newCount);
        return rows > 0 ? "更新成功" : "更新失败";
    }

    // 6. 物理删除错题
    @DeleteMapping("/wrong-questions/{id}")
    public String deleteWrongQuestion(@PathVariable Long id) {
        int rows = wrongQuestionService.deleteWrongQuestion(id);
        return rows > 0 ? "删除成功" : "删除失败";
    }

    @GetMapping("/weak-points")
    public Map<String, Object> getWeakPoints(
            @RequestParam Long userId,
            @RequestParam(required = false) Integer subjectId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return wrongQuestionService.getWeakPointsByUserId(userId, subjectId, page, size);
    }

    // 切换收藏状态
    @PostMapping("/wrong-questions/toggle-favorite")
    public ResponseEntity<?> toggleFavorite(@RequestBody Map<String, Object> request) {
        try {
            // 打印接收到的请求数据，用于调试
            System.out.println("Received request: " + request);
            
            // 获取并转换参数
            Long userId = null;
            Long questionId = null;
            Boolean isFavorite = null;
            
            try {
                if (request.get("userId") instanceof Number) {
                    userId = ((Number) request.get("userId")).longValue();
                } else {
                    userId = Long.parseLong(request.get("userId").toString());
                }
                
                if (request.get("questionId") instanceof Number) {
                    questionId = ((Number) request.get("questionId")).longValue();
                } else {
                    questionId = Long.parseLong(request.get("questionId").toString());
                }
                
                isFavorite = Boolean.parseBoolean(request.get("isFavorite").toString());
            } catch (Exception e) {
                System.out.println("Error parsing parameters: " + e.getMessage());
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "参数格式错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证参数
            if (userId == null || questionId == null || isFavorite == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "缺少必要参数");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success;
            if (isFavorite) {
                success = favoriteZService.addFavorite(userId, questionId);
            } else {
                success = favoriteZService.removeFavorite(userId, questionId);
            }
            
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", isFavorite ? "收藏成功" : "取消收藏成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "操作失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            System.out.println("Error in toggleFavorite: " + e.getMessage());
            e.printStackTrace();
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "操作失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 调试接口
    @GetMapping("/wrong-questions/debug")
    public ResponseEntity<?> debugData() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 检查科目数据
            result.put("subjects", wrongQuestionMapper.checkSubjects());
            
            // 检查错题数据
            result.put("wrongQuestions", wrongQuestionMapper.checkWrongQuestions());
            
            // 检查错题与科目的关联
            result.put("wrongQuestionsWithSubjects", wrongQuestionMapper.checkWrongQuestionsWithSubjects());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("调试数据获取失败: " + e.getMessage());
        }
    }
}
